# -*- coding: utf-8 -*-

'''eof
name:近1年全国正面政策条数
code:Industry_Score_1
tableName:
columnName:
groups:行业评分模块
dependencies:INDUSTRY_INFO
type:常用指标
datasourceType:在线指标
description:
eof'''

from dateutil.relativedelta import relativedelta
from dateutil.parser import parse
import datetime
import pandas as pd

null_type_list = ['', None, 'None', 'null', 'Null', 'NULL', '/', ' ',[]]

def timeCompare(a):
    List = list(a)
    result = []
    for i in List:
        try:
            if parse(i).date() > (datetime.datetime.now().date() - relativedelta(years=1)):
                result.append(True)
            else:
                result.append(False)
        except:
            result.append(None)
    if len(List) == result.count(None):
        raise RuntimeError(u"发布日期字段解析全部失败") 
    return result

def sentiCompare(a):
    List = list(a)
    result = []
    for i in List:
        if i in [1,"1"]:
            result.append(True)
        elif i in [2,"2"]:
            result.append(False)
        else:
            result.append(None)
    if len(List) == result.count(None):
        raise RuntimeError(u"情绪正负面字段解析全部失败") 
    return result

def regionCompare1(a):
    List = list(a)
    result = []
    for i in List:
        if  u"中国" in i:
            result.append(True)
        elif i not in null_type_list:
            result.append(False)
        else:
            result.append(None)
    if len(List) == result.count(None):
        raise RuntimeError(u"地区字段解析全部失败") 
    return result

def Industry_Score_1():
    data = INDUSTRY_INFO.get("data")
    if data in null_type_list:
        return u"缺失值"
    else:
        policyDetail = data.get("policyDetail")
        if policyDetail == []:
            return 0
        if policyDetail in null_type_list:
            return u"缺失值"
        else:
            DATA = pd.DataFrame(policyDetail)
            DATA["dateResult"] = timeCompare(DATA["releaseDate"])
            DATA["posResult"] = sentiCompare(DATA["sentimentPos"])
            DATA["regionResult"] = regionCompare1(DATA["region"])
            DATA = DATA[DATA["dateResult"].isin([True,False]) & DATA["posResult"].isin([True,False]) & DATA["regionResult"].isin([True,False])]
            if len(DATA) == 0:
                raise RuntimeError(u"数据有误") 
            DATA = DATA[DATA["dateResult"].isin([True]) & DATA["posResult"].isin([True]) & DATA["regionResult"].isin([True])]
            if len(DATA) == 0:
                return 0
            DATA = DATA.dropna(subset=['title'])
            if len(DATA) == 0:
                return u"缺失值"
            DATA = DATA.drop_duplicates(subset=['title'])
            length = len(DATA)
            for m in DATA['title']:
                if m in null_type_list:
                    length -= 1
            if length == 0:
                return u"缺失值"
            return length

result = Industry_Score_1()
